<template>
  <div class="login_container">
    <div class="login_box">
      <!-- 头像区域 -->
      <div class="avatar_box">
        <img src="../assets/logo.png" alt="" />
      </div>
      <!-- 登录表单区域 -->
      <el-form v-loading="loading" element-loading-text="登录中......" ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="100px" class="login_form">
        <!-- 用户名 -->
        <el-form-item label="用户昵称：" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户昵称" clearable />
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="用户密码：" prop="password">
          <el-input @focus="showCaptcha=true" @keyup.enter="submitForm(userFormRef)" v-model="userForm.password" type="password" placeholder="请输入用户密码" show-password />
        </el-form-item>
        <el-form-item>
          <mi-captcha ref="captchaRef" v-if="showCaptcha" :width="310" :onSuccess="captchaValidSuccess" theme-color="#2db7f5" image="../src/assets/validImage.jpg" logo="../src/assets/logo.png"></mi-captcha>
        </el-form-item>
        <!-- 按钮区域 -->
        <el-row justify="end">
          <el-form-item>
            <el-button type="primary" @click="submitForm(userFormRef)">登录</el-button>
            <el-button type="info" @click="resetForm(userFormRef)">重置</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
//获取全局发送请求的对象
import {getCurrentInstance, reactive, ref, toRefs} from "vue";
import {ElMessage, FormInstance, FormRules} from "element-plus";
import {useRoute, useRouter} from "vue-router";

const http = getCurrentInstance()?.appContext.config.globalProperties.$http

// -----------响应式数据部分开始----------
// 登录用户对象
const userForm = reactive({
  username: '',
  password: ''
})

const {username, password} = toRefs(userForm)

// 编程式路由对象
const router = useRouter()
const route = useRoute()

// 加载
const loading = ref(false)

// 是否显示验证码
const showCaptcha = ref(false)
// 验证码是否验证通过
const validVal = ref(false)
// 验证码引用对象
const captchaRef = ref()

// 表单引用对象
const userFormRef = ref<FormInstance>()

// 表单校验规则
const userFormRules = reactive<FormRules>({
  username: [
    { required: true, message: '用户名必须输入', trigger: 'blur' },
    { min: 3, max: 15, message: '用户名长度在3-15位之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '用户密码必须输入', trigger: 'blur' },
  ]
})
// -----------响应式数据部分结束----------

// -----------方法部分开始----------
// 用户登录
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid && validVal.value) {
      // 登录加载
      loading.value = true
      if (userForm.username === '' || userForm.password === '') return ElMessage.error('请输入用户或密码！')
      const {data:res} = await http.post('/loginUser', userForm)
      if (res.code !== 200){
        loading.value = false
        // 验证失败重置验证结果
        validVal.value = false
        captchaRef.value.reset()
        return ElMessage.error({showClose: true, message: res.mes})
      } else {
        loading.value = false
        // 验证成功重置验证结果
        validVal.value = false
        ElMessage.success({showClose: true, message: res.mes})
        router.replace('/home')
        // 保存token 密码置为空
        userForm.password = ''
        return localStorage.setItem('token', JSON.stringify(userForm))
      }
    } else {
      ElMessage.error('请输入合法的内容，或通过验证！')
    }
  })
}

// 表单重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  showCaptcha.value = false
}


const captchaValidSuccess = () => {
  validVal.value = true
  submitForm(userFormRef.value)
}
// -----------方法部分结束----------




</script>

<style lang="less" scoped>
.login_container {
  width: 100%;
}
.login_box {
  // 宽450像素
  width: 450px;
  // 高300像素
  height: 300px;
  // 背景颜色
  background-color: #fff;
  // 圆角边框3像素
  border-radius: 3px;
  // 绝对定位
  position: absolute;
  // 距离左则50%
  left: 50%;
  // 上面距离50%
  top: 50%;
  // 进行位移，并且在横轴上位移-50%，纵轴也位移-50%
  transform: translate(-50%, -50%);
  .avatar_box {
    // 盒子高度130像素
    height: 130px;
    // 宽度130像素
    width: 130px;
    // 边框线1像素 实线
    border: 1px solid #eee;
    // 圆角
    border-radius: 50%;
    // 内padding
    padding: 10px;
    // 添加阴影 向外扩散10像素 颜色ddd
    box-shadow: 0 0 10px #ddd;
    // 绝对定位
    position: absolute;
    // 距离左则
    left: 50%;
    // 位移
    transform: translate(-50%, -50%);
    // 背景
    background-color: #fff;
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eee;
    }
  }
}
.login_form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

</style>
